<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="params.enterName" placeholder="企业名称" style="width: 300px;" class="filter-item" size="medium" @keyup.enter.native="handleFilter" clearable/>
      <el-select v-model="params.channelCode" placeholder="渠道名称" v-if="userTypeCode == 1" clearable class="filter-item" size="medium" style="width: 300px;margin-left: 10px">
        <el-option v-for="item in channelList" :key="item.channelCode" :label="item.channelName" :value="item.channelCode" />
      </el-select>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" size="medium" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" size="medium" icon="el-icon-edit-outline" v-if="userTypeCode != 3" @click="handleCreate">
        创建
      </el-button>
    </div>
    <el-table
      :data="list"
      border
      v-loading="listLoading"
      style="width: 100%">
      <el-table-column type="index" align="center" label="序号" width="50"></el-table-column>
      <el-table-column
        prop="enterName"
        label="企业名称"
        style="width:12%">
      </el-table-column>
      <el-table-column
        prop="address"
        label="企业地址"
        style="width: 12%">
      </el-table-column>
      <el-table-column
        prop="contactsUser"
        label="联系人"
        style="width: 5%">
      </el-table-column>
      <el-table-column
        label="审核状态"
        style="width: 4%">
        <template slot-scope="{row}">
          <el-tag :type="row.audit | statusFilter">
            {{ auditStatue(row.audit)}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="contactsPhone"
        label="联系电话"
        style="width: 9%">
      </el-table-column>
      <!-- <el-table-column
        fixed
        label="企业LOGO"
        style="width: 7%">
        <template slot-scope="scope">
          <a :href="scope.row.logo" target="_blank" class="buttonText">图片地址</a>
        </template>
      </el-table-column> -->
      <el-table-column
        prop="logo"
        header-align="center"
        align="center"
        label="企业LOGO">
        <template slot-scope="scope">
          <el-popover placement="top" title="" trigger="hover">
            <img style="max-height: 500px;max-width: 730px" :src="getImgUrl(scope.row.logo)" />
            <img slot="reference" :src="getImgUrl(scope.row.logo)" :alt="scope.row.logo" style="max-height: 50px;max-width: 130px"/>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        prop="syndromes"
        header-align="center"
        align="center"
        label="三证合一">
        <template slot-scope="scope">
          <el-popover placement="top" title="" trigger="hover">
            <img style="max-height: 500px;max-width: 730px" :src="getImgUrl(scope.row.syndromes)" />
            <img slot="reference" :src="getImgUrl(scope.row.syndromes)" :alt="scope.row.syndromes" style="max-height: 50px;max-width: 130px"/>
          </el-popover>
        </template>
      </el-table-column>
      <!-- <el-table-column
        fixed
        label="三证合一"
        style="width: 7%">
        <template slot-scope="scope">
          <a :href="scope.row.syndromes" target="_blank" class="buttonText">图片地址</a>
        </template>
      </el-table-column> -->

      <el-table-column prop="officalUrl" label="公司官网" style="width: 16%"></el-table-column>
      <el-table-column
        label="操作"
        style="width: 22%">
        <template  slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)"> 编辑 </el-button>
          <el-button  size="mini" type="danger" @click="handleDelete(row,$index)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="params.page" :limit.sync="params.limit" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width='500'>
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px" style="margin: 0 40px;">
        <el-form-item label="企业名称" prop="enterName">
          <el-input v-model="temp.enterName" clearable placeholder="请输入企业名称"/>
        </el-form-item>
        <el-form-item label="企业地址" prop="address">
          <el-input v-model="temp.address" clearable placeholder="请输入企业地址"/>
        </el-form-item>
        <el-form-item label="联系人" prop="contactsUser">
          <el-input v-model="temp.contactsUser" clearable placeholder="请填写联系人"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="">
          <!-- <el-input v-model.number="temp.contactsPhone" :maxlength="11" onkeyup="this.value = this.value.replace(/[^\d.]/g,'');" clearable/> -->
          <el-input v-model="temp.contactsPhone" clearable placeholder="请填写联系电话"/>
        </el-form-item>
        <el-form-item label="信用编号" prop="creditNumber">
          <el-input v-model="temp.creditNumber" clearable placeholder="请填写信用编号"/>
        </el-form-item>
        <el-form-item label="用户名" prop="userName" v-if="dialogStatus != 'update'">
          <el-input v-model="temp.userName" clearable placeholder="请填写用户名"/>
        </el-form-item>
        <el-form-item label="3证合一" prop='syndromes'>
          <upload :fileList="picFileList" :limit="1" :multiple="false" @getImg="getPicFileList"></upload>
        </el-form-item>
        <el-form-item label="企业logo" prop='logo'>
          <upload :fileListArr="picFileListArr" :type='1' :limit="1" :multiple="false" @getImgArr="getPicFileListArr"></upload>
        </el-form-item>
        <el-form-item label="官网地址">
          <el-input v-model="temp.officalUrl" clearable placeholder="请填写官网地址"/>
        </el-form-item>
        <el-form-item label='公众号' prop="appId">
          <el-select v-model="temp.appId" class="filter-item" placeholder="请选择" clearable style="width: 100%">
            <el-option v-for="item in allGZH" :key="item.authorizerAppId" :label="item.nickName" :value="item.authorizerAppId" />
          </el-select>
        </el-form-item>
        <el-form-item label='商户号'>
          <el-select v-model="temp.mchId" class="filter-item" placeholder="请选择" clearable style="width: 100%">
            <el-option v-for="item in allSHH" :key="item.mchId" :label="item.payAccountName":value="item.mchId" />
          </el-select>
        </el-form-item>
        <el-form-item label='所属渠道' prop="channelCode">
          <el-select v-model="temp.channelCode" class="filter-item" placeholder="请选择" clearable style="width: 100%">
            <el-option v-for="item in channelList" :key="item.channelCode" :label="item.channelName" :value="item.channelCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="企业介绍" prop="content">
          <el-card style="height: 340px;">
            <quill-editor v-model="content" ref="myQuillEditor" style="height: 180px;" :options="editorOption">
            </quill-editor>
          </el-card>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { getEntertList ,createChannel,deleteEnterInfo,updateEnterInfo,getAllOpenList,getAllPayList } from '@/api/enter'
  import Pagination from '@/components/Pagination'
  import { getChannelList } from '@/api/channel/channelRole'
  import Upload from "@/components/upload/index";
  import { quillEditor} from 'vue-quill-editor'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  export default {
    name: 'info',
    components: { Pagination,Upload,quillEditor },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        msg: '企业信息',
        list: [],
        allGZH: [],//公众号
        allSHH: [],//商户号
        picFileList: [],
        picFileListArr: [],
        listLoading: false,
        dialogImageUrl: '',
        dialogVisible: false,
        channelList: [],
        total: 0,
        content: null,
        editorOption: {},
        params:{
          enterName:'',
          channelCode: '',
          page:1,
          limit:10,
        },
        dialogStatus: '',
        temp: {
          id: undefined,
          appId: '',
          mchId: '',
          enterName: '',
          address: '',
          contactsUser: '',
          contactsPhone: '',
          creditNumber: '',
          syndromes: '',
          userName: '',
          logo: '',
          introduce: '',
          channelCode: '',
          officalUrl: ''
        },
        rules: {
          enterName: [{ required: true, message: '企业名称必填' }],
          address: [{ required: true, message: '企业地址必填' }],
          contactsUser: [{ required: true, message: '联系人必填' }],
          contactsPhone: [
            { required: true, message: '联系电话必填' },
            { pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'},
          ],
          userName: [{ required: true, message: '用户名必填' }],
          creditNumber: [{ required: true, message: '信用编号必填' }],
          appId: [{ required: true, message: '请选择公众号!' }],
          // mchId: [{ required: true, message: '请选择商户号!' }],
          channelCode: [{ required: true, message: '请选择所属渠道' }],
          syndromes: [{ required: true, message: '请上传三证图片' }],
          logo: [{ required: true, message: '请上传logo图片' }]
        },
        dialogFormVisible: false,
        textMap: {
          update: '编辑企业信息',
          create: '创建企业信息'
        },
        getToken: '',
        userTypeCode: '',//用户角色UT001平台 UT002渠道 UT003企业
      }
    },
    created() {
     // console.log(this.$store.user.usernameKey)
      this.getList()
      getChannelList().then(response => {
        this.channelList = response.data
      })
      this.userTypeCode = sessionStorage.getItem("userTypeCode").substring(4,5)  || '';
    },
    methods: {
      resetTemp() {
        this.temp = {
          id: undefined,
          enterName: '',
          address: '',
          contactsUser: '',
          contactsPhone: '',
          creditNumber: '',
          syndromes: '',
          userName: '',
          introduce: '',
          appId: '',
          mchId: '',
          logo: '',
          channelCode: '',
          officalUrl: ''
        }
      },
      //table图片回显
      getImgUrl(icon){
        return "//"+icon;
      },
      auditStatue(statue){
        return statue == 1 ? '通过' : '已审核'
      },
      handleFilter() {
        this.params.page = 1
        this.getList()
      },
      getPicFileList(imgList) {
        this.picFileList = imgList;
        if(imgList && imgList.length > 0){
          this.temp.syndromes = imgList[0].response.data;
        }
      },
      getPicFileListArr(imgList1) {
        this.picFileListArr = imgList1;
        if(imgList1 && imgList1.length > 0){
          this.temp.logo = imgList1[0].response.data;
        }
      },
      handleUpdate(row) {
        this.picFileList = []
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.content = row.introduce || null
        this.picFileList = [{name:'', url: '//' + this.temp.syndromes, response:{url: '//' + this.temp.syndromes}}];
        this.picFileListArr = [{name:'', url: '//' + this.temp.logo, response:{url: '//' + this.temp.logo}}];
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        this.toGetAllList()
        this.toGetAllPayList()
        // this.temp.channelCode = sessionStorage.getItem("channelCode") || '';
        // getChannelList().then(response => {
        //   this.channelList = response.data
        // })
      },
      handleCreate() {
        this.picFileList = []
        this.picFileListArr = []
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.content = null
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
        this.temp.channelCode = sessionStorage.getItem("channelCode") || '';
        // getChannelList().then(response => {
        //   this.channelList = response.data
        // })
        this.toGetAllList()
        this.toGetAllPayList()
      },
      updateData(){
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.introduce = this.content;
            const tempData = Object.assign({}, this.temp)
            tempData.type=2
            updateEnterInfo(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.introduce = this.content;
            createChannel(this.temp).then(response=> {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleDelete(row, index) {
        let element = this.list[index]
        let data=[element.id];
        this.$confirm('确定删除该条数据？','提示', {
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteEnterInfo(data).then(response =>{
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
            this.getList()
          })
        }).catch(() => {
                  
        });
        
      },
      getList() {
        this.listLoading = true
        getEntertList(this.params).then(response =>{
          this.list=response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      },
      //查询所有公众号getAllList
      toGetAllList(){
        getAllOpenList({limit: 999,page: 1}).then(response =>{
          this.allGZH = response.data
        })
      },
      //查询所有商户号
       toGetAllPayList(){
        getAllPayList({limit: 999,page: 1}).then(response =>{
          this.allSHH = response.data
        })
      },
      //企业logo
      beforeAvatarUpload(file){
        // console.log('------------',file)
      },
      handleAvatarSuccess(res, file) {
        // console.log('444444444444',res, file)
       this.temp.logo = res.data;
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
